window.onload=function(){	
	//上传多个图片
	 //为外面的盒子绑定一个点击事件
	var upload = document.getElementById("uploadForm");
    var formdata = new FormData();
    $("#uploadImgBtn").click(function(){
        var $input = $("#file2");
		//1.给input标签绑定change事件
        $input.on("change" , function(){
        //设置multiple属性，因此一次可以上传多个文件,获取选择图片的个数
            var files = this.files;
            var length = files.length;
            console.log(files);
			//2.回显
			//each()方法规定为每个匹配元素规定运行的函数
            $.each(files,function(key,value){
//          	console.log(key);
                //每次都只会遍历一个图片数据
                var list = document.getElementById("list"),
                	oitem = document.createElement("li");
                oitem.className = "item";
                oitem.id ="wrap"+key;
                oitem.setAttribute("data-num","0");
                oitem.setAttribute("draggable","true"); 
                var read = new FileReader();
                read.onload = function(){               	
                	html ='<div id="target-img'+key+'">'
                		+'<div class="box">'
						+'<img src="'+this.result+'" alt="" class="f-img"/ name="" id="img'+key+'">'
						+'</div>'	
						+'<div class="catah">'
						+'<span class="iconfont del">&#xe669;</span>'
						+'<p class="add">'
						+'<span class="span1">添加注释</span><br />'			
						+'<span class="span2">详情</span>'			
						+'</p>'		
						+'</div></div>';
					oitem.innerHTML = html;
                    list.appendChild(oitem);
                    for(i=0;i<item.length;i++){
						item[i].index = i;
					} 
					//设置图片大小
					var img = oitem.getElementsByTagName('img')[0];  
	                img.onload = function(){  
	                    var nowHeight = ReSizePic(this); //设置图片大小  
	                    this.parentNode.style.display = 'block';  
	                    var oParent = this.parentNode;  
	                    if(nowHeight){  
	                        oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';  
	                    }  
	                }  															
                }
                read.readAsDataURL(value);                
            })
            for(i=0;i<length;i++){
               formdata.append('files',files[i]);  
            }
             //图片排序
		    var imgs = document.getElementById("list").getElementsByTagName("img");
		    console.log(imgs);
		    var arr=[];
		    for(var i=0;i<imgs.length;i++){
		    	arr.push(imgs[i]);
		    }
		    arr.sort(function(a,b){
		    	var a1 = a.name.substring(0,1);
		    	var b1 = b.name.substring(0,1);
		    	console.log(a1);
		    	if(a1>b1){
		    		return 1;
		    	}else if(a1<b1){
		    		return -1;
		    	}else{
		    		return 0;
		    	}
		    });
		      console.log(arr);
		    for(var i=0;i<arr.length;i++){
		    	formdata.append('imgs',arr[i]);
		    }
		    console.log(arr.length);
		//图片大小验证	    
		    var fileSize = 0;
		    var fileMaxSize = 1024;//1M
		    var osize = document.getElementsByClassName("file2");
		    var filePath = osize.value;
		    if(filePath){
		        fileSize =osize.files[0].size;
		        var size = fileSize / 1024;
		        console.log(size);
		        if (size > fileMaxSize) {
		            alert("文件大小不能大于1M！");
		            osize.value = "";
		            return false;
		        }else if (size <= 0) {
		            alert("文件大小不能为0M！");
		            osize.value = "";
		            return false;
		        }
		    }else{
		        return false;
		    }
        })
        $input.removeAttr("id");
        //我们做个标记，再class中再添加一个类名就叫test
        var newInput = '<input class="file2 test" type="file"  multiple id="file2" form="uploadForm">';
        $(this).append($(newInput));
    //------回显图片并遍历---------     	
    })
    
	//遍历每一张图片
	var catah = document.getElementsByClassName('catah');
	var title = document.getElementsByClassName('title')[0];
	var meng = document.getElementById("meng");
	var item = document.getElementsByClassName("item");
	var list = document.getElementById("list");
	var add = document.getElementsByClassName(".add");
	var inAdd = 0;  //设置一个全局变量的值
	for(i=0;i<item.length;i++){
		item[i].index = i;
	}	
	$('#list').on('click','.item',function(e) {
		var index = this.index;
			inAdd = this.index;
    	var onum = $(this).attr('data-num');
    	$(this).off('mouseover');
    	if(onum == "0"){
    		catah[index].style.display='block';
    		title.style.display='block';
    		meng.style.display="block";
    		$(this).attr('data-num','1');
    	}else{
    		catah[index].style.display='none';
    		title.style.display='none';
    		meng.style.display="none";
    		$(this).attr('data-num','0');
    	}
     //中间输入框title的偏移量  
 		var ow = item.offsetWidth-(title.offsetWidth/2);
        var offsetLeft= this.offsetLeft-ow;
        var offsetTop = this.offsetTop+this.offsetHeight;
        title.style.top=offsetTop+'px';
        if(offsetLeft<0){
        	title.style.left=0;    		
        }else{
        	title.style.left=offsetLeft+'px';
        }
    });  
    //删除一张照片
    $('#list').on('click','.del',function(e){    	
    	e.stopPropagation();
//  	var files = $("#file2").index;
    	var inDel = this.parentNode.index;
    	console.log(inDel);
    	$(this).parents('li').remove(inDel);
    	for(i=0;i<item.length;i++){
			item[i].index = i;
		}
	});	
   //添加注释到照片中去  
    $(".submit").on('click',function(){       
    	$(item[inAdd]).find(".span1").html($(".p-biao").val());
    	$(item[inAdd]).find(".span2").html($(".p-xiang").val());
    	$(".p-biao").val("");
    	$(".p-xiang").val("");
    })
    //蒙版
    $("#meng").on('click',function(){   	
    	catah[inAdd].style.display="none";
    	title.style.display='none';
    	meng.style.display="none";
    	$(item[inAdd]).attr('data-num','0');
    })
    //显示注释
    $('#list').on('mouseover','.item',function(e) {
   		var index = this.index;
    	catah[index].style.display='block';
    })
    $('#list').on('mouseout','.item',function(e) {
   		var index = this.index;
    	catah[index].style.display='none';
    })
    //拖拽图片
    //监听事件
	const dragCon = document.getElementById('list');
	dragCon.addEventListener('dragstart',startDrag,false);
	//阻止dragover的默认行为
	dragCon.addEventListener('dragover',function(e){
		e.preventDefault();
	},false);
	dragCon.addEventListener('drop',exchangeElement,false);
	//在dragstart事件中，我们需要记住需要交换的子元素和父元素
	function startDrag(e){
		e.dataTransfer.setData('Text',e.target.parentElement.parentElement.id +';'+e.target.parentElement.parentElement.parentElement.id);
		console.log(e);
	}
	//最重要的就是在drop事件中处理我们交换元素的逻辑和一些边缘条件的判断
	function exchangeElement(e){
		e.preventDefault();
		const el = e.target;
		console.log(el);
		let PE,//要插入位置的父元素
			CE;//需要交换的元素
		if (el.tagName.toLowerCase() !== 'li') {  
			PE = el.parentElement.parentElement.parentElement;
		    CE = el.parentElement.parentElement;
		} else {
		    PE = el.parentElement.parentElement;
		    CE = el.parentElement.parentElement.querySelector('img');
		}
		console.log(PE);//目标位置元素的父元素
		console.log(CE);//目标位置元素
		  /**
		   * 判断不在控制范围内
		   */
		if (!PE.classList.contains('item')) {  //判断是否存在类item
		    return;
		}
		var data = e.dataTransfer.getData('Text').split(';');
		console.log(data);
		  //交换元素
		  //data[0]保存的是选中的要移动位置的元素的子元素的id
		 //data[1]保存的是选中的要移动位置的元素的id
		document.getElementById(data[1]).appendChild(CE);
		PE.appendChild(document.getElementById(data[0]));
	}
    //提交表单    
	$("#btn").on('click',function(){
		var item = document.getElementsByClassName("item");
		var otext = document.getElementById("text");
		var teacher = document.getElementById("teacher");
		var draw = document.getElementById("draw");
		var cont = document.getElementById("cont");	
		var oImg = document.getElementById("file");
		formdata.append("imag",oImg.files[0]);//封面
		formdata.append("ftsTitle",otext.value);//标题名称		
		formdata.append("teacherName",teacher.value);//老师
		formdata.append("typeOne",draw.value);	//艺术专业一
		formdata.append("typeTwo",cont.value);	//艺术专业二	
		var spans = '';
		//循环取出span1的值
		$(".add").each(function(i, obj){
			var pictureTitle= document.getElementsByClassName('span1')[i];
			spans+=pictureTitle.innerHTML+',';
		});	
		if(!spans){
			spans='null';
		}
		var ospans = '';		
		//循环取出span2的值
		$(".add").each(function(i, obj){
			var pictureDescription = document.getElementsByClassName('span2')[i];
			ospans+=pictureDescription.innerHTML+',';
		});
		if(!ospans){
			ospans='null';
		}
		formdata.append('pictureTitle',spans);//图片标题
		formdata.append('pictureDescription',ospans);//图片详情
		/*formdata.append('token','5e3d2ba4766a23bd3c6fd039d92d7954');*/
		//判断封面是否上传
		if(oImg.value==''){
			alert("请上传封面");
			return false;
		}				   
		$.ajax({
			type:"post",
			url:path+'/ftp/followThePainting_save',			
			dataType:"json",
			data:formdata, 
	        cache: false,  
	        contentType: false,  
	        processData: false,
	        clearForm: true,//提交后是否清空表单数据
			success:function(data){
				if(data.code == "200"){
					 layer.msg('操作成功!',{icon:1,time:1000},function(){
                   	  parent.window.location.reload();
                   });
				}else if(data.code == "500"){
					layer.alert("上传失败！");
 				}
			},
			error:function(err){
				console.log(err);
			}
		});
		
	})
    function ReSizePic(ThisPic) {  
	    var RePicWidth = 200; //这里修改为您想显示的宽度值  	  
	    var TrueWidth = ThisPic.width; //图片实际宽度  
	    var TrueHeight = ThisPic.height; //图片实际高度  	      
	    if(TrueWidth>TrueHeight){  
	        //宽大于高  
	        var reWidth = RePicWidth;  
	        ThisPic.width = reWidth;  
	        //垂直居中  
	        var nowHeight = TrueHeight * (reWidth/TrueWidth);  
	        return nowHeight;  //将图片修改后的高度返回，供垂直居中用  
	    }else{  
	        //宽小于高  
	        var reHeight = RePicWidth;  
	        ThisPic.height = reHeight;  
	    }  
	}
}
